<?php
/**
 * Created by PhpStorm.
 * User: JHR
 * Date: 2018/9/20
 * Time: 16:36
 */
namespace app\api\controller;
use think\facade\Cache;
use think\Db;
use think\exception\HttpResponseException;

class Wechat extends Base {
    /**
     * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
     * @return array 微信用户信息数组
     */
    public function auth_base(){
        $param = input('param.');
        if (!isset($_GET['code'])){ //没有code，去微信接口获取code码
            $callback = $_SERVER['REQUEST_SCHEME'] . '://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $this->get_code($callback,'snsapi_base');
        } else {    //获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            if(isset($param['backurl'])) {
                $query_data = [
                    'openid' => $data['openid']
                ];
                $backurl = url_reset($param['backurl'],$query_data);
                header('Location:'. $backurl);exit();
            }
        }
    }

    public function auth_user(){
        if (!isset($_GET['code'])){ //没有code，去微信接口获取code码
            $callback = $_SERVER['REQUEST_SCHEME'] . '://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $this->get_code($callback);
        } else {    //获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            $data_all = $this->get_user_info($data['access_token'],$data['openid']);//获取微信用户信息
            $user_exist = Db::table('mp_user_wechat')->where('openid',$data_all['openid'])->find();
            $time = time();
            $uid = '';
            if($user_exist) {
                if($user_exist['uid']) {
                    $uid = $user_exist['uid'];
                }
                $update_data = [
                    'openid' => $data_all['openid'],
                    'nickname' => $data_all['nickname'],
                    'avatar' => $data_all['headimgurl'],
                    'gender' => $data_all['sex'],
                    'update_time' => $time
                ];
                Db::table('mp_user_wechat')->where('openid',$data_all['openid'])->update($update_data);
            }else {
                $insert_data = [
                    'openid' => $data_all['openid'],
                    'nickname' => $data_all['nickname'],
                    'avatar' => $data_all['headimgurl'],
                    'gender' => $data_all['sex'],
                    'create_time' => $time,
                    'update_time' => $time
                ];
                Db::table('mp_user_wechat')->insertGetId($insert_data);
            }

            $token = md5($data_all['openid'] . $time);
            $whereToken = [
                ['wx_openid','=',$data_all['openid']]
            ];
            $token_exist = Db::table('mp_token')->where($whereToken)->find();
            if(!$token_exist) {
                $insert_data = [
                    'wx_openid' => $data_all['openid'],
                    'token' => $token,
                    'create_time' => $time,
                    'login_type' => 2
                ];
                if($uid) {
                    $insert_data['uid'] = $uid;
                }
                Db::table('mp_token')->insert($insert_data);
            }else {
                $update_data = [
                    'wx_openid' => $data_all['openid'],
                    'token' => $token,
                    'create_time' => $time,
                    'login_type' => 2
                ];
                if($uid) {
                    $update_data['uid'] = $uid;
                }
                Db::table('mp_token')->where($whereToken)->update($update_data);
            }
            if(isset($_GET['backurl'])) {
                $query_data = [
                    'openid' => $data_all['openid'],
                    'uid' => $uid,
                    'token' => $token
                ];
                $backurl = url_reset($_GET['backurl'],$query_data);
                header('Location:'. $backurl);exit();
            }
            exit('login success');
        }

    }
    /**
     * 2、用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    private function get_code($callback,$scope = 'snsapi_userinfo'){
        $appid = config('appid');
        $state = md5(uniqid(rand(), true));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:".$url);exit;
    }
    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code){
        $appid = config('appid');
        $appsecret = config('app_secret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            if($user->errcode == '40163') {
//                    echo 'Code been used!';exit;
                throw new HttpResponseException(ajax('Code been used!',-1));
            }else {
//                    echo 'error:' . $user->errcode.'<hr>msg :' . $user->errmsg;exit;
                throw new HttpResponseException(ajax($user->errmsg,-1));
            }
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }
    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    private function get_user_info($access_token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
//            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
            throw new HttpResponseException(ajax($user->errmsg,49));
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }

    public function getCode() {
        if(!isset($_GET['code'])) {
            $callback = $_SERVER['REQUEST_SCHEME'] . '://'.$_SERVER['HTTP_HOST'] . '/api/login/getCode';  //微信服务器回调url，这里是本页url
            $this->get_code($callback);
        }else {
            echo($_GET['code']);
        }
    }



}